package com.snails.net;

import android.content.Context;
import android.text.TextUtils;

import com.snails.net.restful.configuration.IConfiguration;
import com.snails.net.utils.NetworkUtil;

/**
 * 网络 快速框架
 *
 * @author lawrence
 * @date 2019-04-11  18:41:36
 * <p>
 * 使用：
 * 1、需先调用SnailsNet.instance().init()初始化
 */

public class SnailsNet {
    private static volatile SnailsNet instance = null;
    private Context ctx = null;
    private String baseUrl = "";
    private IConfiguration iConfiguration = null;

    public static SnailsNet instance() {
        if (instance == null) {
            synchronized (SnailsNet.class) {
                if (instance == null)
                    instance = new SnailsNet();
            }
        }
        return instance;
    }

    // ================================================================================
    // --- ---
    // ================================================================================
    /**
     * 初始化SnailsApp陪住
     * @param ctx   application
     * @param baseUrl   网络请求host
     * @param configuration app配置
     */
    public void init(Context ctx, String baseUrl, IConfiguration configuration) {
        checkInit(ctx, baseUrl, configuration);
        this.baseUrl = baseUrl;
        this.iConfiguration = configuration;
        initial(this.ctx = ctx.getApplicationContext());
    }

    public Context getCtx() {
        return ctx;
    }

    public String baseUrl() {
        return this.baseUrl;
    }

    public IConfiguration configuration() {
        return iConfiguration;
    }

    // ================================================================================
    // --- ---
    // ================================================================================
    // 检查参数有效性
    private void checkInit(Context ctx, String baseUrl, IConfiguration configuration) {
        if (ctx == null) {
            throw new NullPointerException("net-ctx 不能为 null");
        }
        if (TextUtils.isEmpty(baseUrl)) {
            throw new NullPointerException("net-baseUrl 不能为 null");
        }
        if (configuration == null) {
            throw new NullPointerException("net-configuration 不能为 null");
        } else if (configuration.restful() == null) {
            throw new NullPointerException("net-configuration中restful未设置");
        }
    }

    // ================================================================================
    // --- ---
    // ================================================================================
    private SnailsNet() { }

    // 对需要Context的数据初始化
    private void initial(Context ctx) {
        NetworkUtil.init(ctx);          // 初始化网络信息
    }

}
